const db = require('../config/db')
const categoryDetailModel = '../schema/category_detail'
const categoryModel = '../schema/category'

const Mall = db.MallSequelize
const category = Mall.import(categoryModel)
const category_detail = Mall.import(categoryDetailModel)
category.hasMany(category_detail)
category_detail.belongsTo(category)
// 获取商品类别明细
const getCategoryDetails = async (query) => {
  let page = Number(query.page)
  let limit = Number(query.limit)
  const result = await category_detail.findAndCountAll(
    {
      include: [category],
      order: [['created_at', 'desc']],
      offset: parseInt(page*10)*parseInt(limit/10),
      limit: limit,
      where: {
        status: 1
      }
    }
  )
  return result
}
// 根据id获取商品类别明细
const getCategoryDetailById = async (id) => {
  const result = await category_detail.findAll(
    {
      include: [category],
      where: {id: id}
    }
  )
  return result
}
// 添加商品明细
const addCategoryDetail = async (data) => {
  await category_detail.create({
    name: data.name,
    status: 1,
    category_id: data.category_id,
    image_url: data.image_url
  })
  return true
}
// 修改商品明细
const updateCategoryDetail = async (data, id) => {
  await category_detail.update(
    {
      name: data.name,
      status: data.status,
      category_id: data.category_id,
      image_url: data.image_url
    },
    {
      where: {id: id}
    }
  )
  return true
}
// 根据搜索关键字获取商品类别明细
const getDetailByKeyWords = async (keywords) => {
  if(keywords.id) {
    const result = await category_detail.findAll(
      { 
        include: [category],
        where: {
          id: Number(keywords.id)
        } 
      },
    )
    return result
  }else if(keywords.name) {
    const result = await category_detail.findAll(
      { 
        include: [category],
        where: {
          name: keywords.name
        } 
      },
    )
    return result
  }
}
// 删除明细
const deleteCategoryDetail = async (id) => {
  await category_detail.update(
    {
      status: 0
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
module.exports = {
  getCategoryDetails,
  getCategoryDetailById,
  addCategoryDetail,
  updateCategoryDetail,
  getDetailByKeyWords,
  deleteCategoryDetail
}